import { myRequest } from "@core/service-api";
import type { ResourceList } from "./type";

function pushResourceList(
  apiData: ResourceList[] = [],
  resourceList: ResourceList[] = []
) {
  apiData.forEach((a) => {
    if (a.children && a.children.length) {
      pushResourceList(a.children, resourceList);
    }
    resourceList.push({
      ...a,
      key: a.key || "",
    });
  });
}
export const getAllMenu = async (systemId: string) => {
  const menus = await myRequest(`/api/uims/v1/resource/getMenu/${systemId}`);
  let resourceList: ResourceList[] = [];

  pushResourceList(menus?.resourceList, resourceList);

  return Promise.resolve(resourceList);
};

export const getCurCategoryId = (
  resourceList: ResourceList[] = [],
  systemId: string,
  slicePoint = 3
) => {
  const pathname = window.location.pathname;

  const pathnameSplit = pathname.split("/").filter(Boolean);
  // 81869552404688911
  // let slicePoint = 3;
  // if(systemId==='81869552404688911'){
  //   slicePoint=2
  // }
  const realPathName = pathnameSplit.slice(slicePoint).join("/");
  const firstId = resourceList.find((r) => r.id);

  if (!realPathName || !realPathName.length) {
    if (import.meta.env.MODE === "development") {
      return firstId?.id;
    } else {
      return "";
    }
  }
  const find = resourceList.find((r) => r.key.indexOf(realPathName) > -1);
  if (find) {
    return find.id;
  } else {
    if (import.meta.env.MODE === "development") {
      return firstId?.id;
    } else {
      return "";
    }
  }
};

export interface ArtListModelDatum {
  id: number;
  createdId?: any;
  createdName?: any;
  createdDatetime?: any;
  modiId?: any;
  modiName?: any;
  modiDatetime?: any;
  tenantId?: any;
  busCode?: any;
  delFlag?: any;
  categoryId?: any;
  channel?: any;
  title: string;
  summary?: any;
  content?: any;
  sortNum?: any;
  platformCode?: any;
  systemId?: any;
  status?: any;
  path: string;
}
export const getArtList = async (data: any): Promise<ArtListModelDatum[]> => {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await myRequest(`/api/cms/v1/help/article-page`, {
        method: "post",
        data,
        headers: {
          "depend-uri": `/api/cms/v1/help/index/1`,
          "depend-method": "GET",
        },
      });

      resolve(res?.rows || []);
    } catch (error) {
      reject({});
    }
  });
};
